package com.unipay.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.unipay.common.utils.BeanUtils;
import com.unipay.hosp.repository.DepartmentRepository;
import com.unipay.hosp.service.DepartmentService;
import com.unipay.model.hosp.Department;
import com.unipay.vo.hosp.DepartmentQueryVo;
import com.unipay.vo.hosp.DepartmentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Project: yitong_parent
 * @Author: C.yu
 * @Time: 2023-04-06 10:48:24
 * @Desc: TODO
 * 医院编号是平台分配的，全局唯一，科室编号为医院自己的编号，相对医院唯一，上传科室接口可以多次调用，
 * 如果医院编号与科室编号组合唯一为更新操作
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void save(Map<String, Object> objectMap) {
        String stringMap = JSONObject.toJSONString(objectMap);
        Department department = JSONObject.parseObject(stringMap, Department.class);
        Department departmentByHoscodeAndDepcode = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        if (null != departmentByHoscodeAndDepcode) {
            BeanUtils.copyBean(department, departmentByHoscodeAndDepcode, Department.class);
        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            departmentRepository.save(department);
        }
    }

    @Override
    public Page<Department> findPageDepartment(int page, int limit, DepartmentQueryVo departmentQueryVo) {
        //TODO 创建Pageable对象，设置当前页和每页记录数
        Pageable pageable = PageRequest.of(page - 1, limit);    // 0---第一页
        //封装条件对象
        Department department = new Department();
        org.springframework.beans.BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);
        //TODO 创建Example对象
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Department> example = Example.of(department, matcher);
        Page<Department> departmentPage = departmentRepository.findAll(example, pageable);
        return departmentPage;
    }

    @Override
    public void remove(String hoscode, String depcode) {
        Department departmentByHoscodeAndDepcode = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        departmentRepository.deleteById(departmentByHoscodeAndDepcode.getId());
    }

    //根据hosp编号，查询医院所有科室列表
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //（1）创建list集合，用于最终封装数据
        List<DepartmentVo> result = new ArrayList<DepartmentVo>();
        //（2）根据hosp编号，查询所有科室信息列表
        Department department = new Department();
        //封装查询条件
        department.setHoscode(hoscode);
        Example example = Example.of(department);
        List<Department> departmentList = departmentRepository.findAll(example);
        //（3）根据大科室编号 bigcode 分组，获取每个大科室里面下级子科室
        //TODO 分组---Java8特性：stream流
        Map<String, List<Department>> departmentMap = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        for (Map.Entry<String, List<Department>> entry: departmentMap.entrySet()){
            //大科室
            DepartmentVo departmentVo = new DepartmentVo();
            String bigCode = entry.getKey();
            List<Department> bigCodeDepartmentList = entry.getValue();
            departmentVo.setDepcode(bigCode);
            departmentVo.setDepname(bigCodeDepartmentList.get(0).getDepname());
            //小科室
            List<DepartmentVo> children = new ArrayList<>();
            for (Department department1: bigCodeDepartmentList){
                DepartmentVo childDepartmentVo = new DepartmentVo();
                childDepartmentVo.setDepcode(department1.getDepcode());
                childDepartmentVo.setDepname(department1.getDepname());
                //封装到集合，
                children.add(childDepartmentVo);
            }
            //小科室list集合，放到大科室
            departmentVo.setChildren(children);
            //放到最终result里面
            result.add(departmentVo);
        }
        return result;
    }

    @Override
    public String getDepname(String hoscode, String depcode) {
        Department departmentByHoscodeAndDepcode = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (departmentByHoscodeAndDepcode != null){
            return departmentByHoscodeAndDepcode.getDepname();
        }
        return null;
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
    }


}
